package utils

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
)

func DesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := des.NewCipher(key)

	if err != nil {
		return nil, err
	}
	origData = PKCS5Padding(origData, block.BlockSize())
	// origData = ZeroPadding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, key)
	crypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化crypted也可以
	// crypted := origData
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func DesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, key)
	origData := make([]byte, len(crypted))
	// origData := crypted
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	// origData = ZeroUnPadding(origData)
	return origData, nil
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

func MakeBlocksFull(src []byte,blockSize int)[]byte{
	length := len(src)
	remains := length%blockSize
	paddingNumber := blockSize -remains
	s1 := []byte{byte(paddingNumber)}
	s2 := bytes.Repeat(s1,paddingNumber)
	s3 := append(src,s2...)
	return s3
}

func MakeBlocksOrigin(src []byte)[]byte{
	length := len(src)
	lastChar := src[length-1]
	number := int(lastChar)
	return src[:length-number]
}

func DecryptByDESAndCBC(cipherText []byte,key,iv string)string{
	textBytes := cipherText
	keyBytes := []byte(key)
	ivBytes := []byte(iv)

	block,err := des.NewCipher(keyBytes)
	if err != nil {
		panic(err)
	}
	blockMode := cipher.NewCBCDecrypter(block,ivBytes)
	blockMode.CryptBlocks(textBytes,textBytes)
	plainText := MakeBlocksOrigin(textBytes)
	return string(plainText)
}